<template>
  <div class="erp-list-form">
    <erp-page-form
      ref="erpPageForm"
      :visible-dialog-form.sync="visible"
      :title="formTitle"
      :form="form"
      :loading="loading"
      :save-loading="buttonLoading"
      :form-configs="config.form"
      :label-suffix="labelSuffix"
      :width="width"
      :height="height"
      :type="type"
      :tab="config.tab"
      :label-width="labelWidthComp"
      @close="handleClose"
      @save="handleSave"
      @fail-validate="handleFailValidate"
      @fetch-pane-height="handleFetchPaneHeight"
    >
      <template slot="tab">
        <el-tab-pane
          v-for="(group, groupIndex) in groupForm"
          :key="groupIndex"
          class="form-group erp-list__form"
          :lazy="true"
        >
          <span slot="label">
            <i
              v-if="groupFailIndexArray && groupFailIndexArray.length > 0 && groupFailIndexArray.indexOf(groupIndex) > -1"
              class="el-icon-warning"
              style="color: #c00;"
            />
            {{ group.title || $t('common.erp.form.basicInfo') }}
          </span>
          <div
            v-for="(box, boxIndex) in group.items"
            :key="boxIndex"
            class="form-box"
            :class="{hasHeader: box.title}"
          >
            <div
              v-if="box.title"
              class="form-box-header"
            >
              <span class="form-box-header-icon" /> {{ box.title }}
            </div>
            <el-row
              v-if="box.items && box.items.length > 0"
              v-show="box.visible === undefined || box.visible"
            >
              <div
                v-for="(item, index) in box.items"
                :key="index"
              >
                <erp-item
                  :xs-col="xsCol"
                  :sm-col="smCol"
                  :md-col="mdCol"
                  :lg-col="lgCol"
                  :xl-col="xlCol"
                  :item="item"
                  :form="form"
                  :label-width="labelWidth(item)"
                  :tab-pane-height="tabPaneHeight"
                  @update-field="handleUpdateField"
                  @value-change="handleValueChange"
                  @change-options="changeOptions($event, item)"
                />
              </div>
            </el-row>
          </div>
        </el-tab-pane>
      </template>
      <template slot="form">
        <div
          v-for="(group, groupIndex) in groupForm"
          :key="groupIndex"
          class="erp-list__form form-group"
        >
          <template slot="label">
            <i
              v-if="groupFailIndexArray && groupFailIndexArray.length > 0 && groupFailIndexArray.indexOf(groupIndex) > -1"
              class="el-icon-warning"
              style="color: #c00;"
            />
            {{ group.title || $t('common.erp.form.basicInfo') }}
          </template>
          <div
            v-for="(box, boxIndex) in group.items"
            :key="boxIndex"
            class="form-box"
            :class="{hasHeader: box.title}"
          >
            <div
              v-if="box.title"
              class="form-box-header"
            >
              <span class="form-box-header-icon" /> {{ box.title }}
            </div>
            <el-row
              v-if="box.items && box.items.length > 0"
              v-show="box.visible === undefined || box.visible"
            >
              <div
                v-for="(item, index) in box.items"
                :key="index"
              >
                <erp-item
                  :xs-col="xsCol"
                  :sm-col="smCol"
                  :md-col="mdCol"
                  :lg-col="lgCol"
                  :xl-col="xlCol"
                  :item="item"
                  :form="form"
                  :label-width="labelWidth(item)"
                  :tab-pane-height="tabPaneHeight"
                  @update-field="handleUpdateField"
                  @value-change="handleValueChange"
                  @change-options="changeOptions($event, item)"
                />
              </div>
            </el-row>
          </div>
        </div>
      </template>
      <template #footer-append>
        <el-button
          v-for="(button, index) in buttons"
          :key="index"
          v-bind="button.props"
          :type="button.props && button.props.type ? button.props.type : 'primary'"
          :loading="button.loading === undefined ? false : button.loading"
          :disabled="disabledButton(button, form)"
          class="erp-list-form-footer-button"
          @click="handleRowAction(button, index)"
        >
          {{ button.text }}
        </el-button>
      </template>
    </erp-page-form>
    <div v-if="components">
      <div>
        <component
          :is="'ErpListForm'"
          v-for="(component, componentKey) in components"
          :key="componentKey"
          :name="component.name"
          :title="component.title"
          :visible-dialog.sync="component.active"
          :query="component.query"
          :page-config-api="component.pageConfigApi"
          :data-source-api="component.dataSourceApi"
          :default-value-api="component.defaultValueApi"
          @close="handleComponentClose(componentKey)"
        />
      </div>
    </div>
  </div>
</template>

<script>
import Vue from 'vue';
import {Card, Divider, FormItem, Input, Radio, Button} from "element-ui";
import {base as request} from '@/request';
import ErpPageForm from '@/components/erp/ErpPageForm';
import {toast, cloneJson, generateGroupForm, uniqueArray} from "@/utils";
import ErpFormCol from "../../../components/erp/ErpPageForm/ErpFormCol";
import ErpFormItem from '@/components/erp/ErpListForm/ErpFormItem';
import ErpItem from '@/components/erp/ErpListForm/ErpItem';
import {generateNewForm, getServerDataSource} from "../../../utils/form";

Vue.use(FormItem);
Vue.use(Radio);
Vue.use(Input);
Vue.use(Card);
Vue.use(Button);
Vue.use(Divider);
const ErpListPage = () => import('@/components/erp/ErpListPage/ErpListPage');
const ErpViewItem = () => import('@/components/erp/ErpListView/ErpViewItem');
/**
 * 列表表单组件
 * @author maolin
 */
export default {
  name: "ErpListForm",
  components: {
    ErpPageForm,
    ErpFormCol,
    ErpFormItem,
    ErpItem,
    ErpListPage,
    ErpViewItem
  },
  props: {
    /**
     * 表单弹窗宽度
     * @public
     */
    width: {
      type: [Number, String],
      default: ''
    },
    /**
     * 表单弹窗高度
     * @public
     */
    height: {
      type: [Number, String],
      default: ''
    },
    /**
     * 表单弹窗类型（modal/drawer）
     * @public
     */
    type: {
      type: String,
      default: 'modal'
    },
    /**
     * <768px 响应式栅格数或者栅格属性对象
     * number/object (例如： {span: 4, offset: 4})
     * @public
     */
    xsCol: {
      type: Object,
      default () {
        return {span: 24};
      }
    },
    /**
     * ≥768px 响应式栅格数或者栅格属性对象
     * number/object (例如： {span: 4, offset: 4})
     * @public
     */
    smCol: {
      type: Object,
      default () {
        return {span: 12};
      }
    },
    /**
     * ≥992px 响应式栅格数或者栅格属性对象
     * number/object (例如： {span: 4, offset: 4})
     * @public
     */
    mdCol: {
      type: Object,
      default () {
        return {span: 8};
      }
    },
    /**
     * ≥1200px 响应式栅格数或者栅格属性对象
     * number/object (例如： {span: 4, offset: 4})
     * @public
     */
    lgCol: {
      type: Object,
      default () {
        return {span: 6};
      }
    },
    /**
     * ≥1920px 响应式栅格数或者栅格属性对象
     * number/object (例如： {span: 4, offset: 4})
     * @public
     */
    xlCol: {
      type: Object,
      default () {
        return {span: 6};
      }
    },
    /**
     * 是否显示弹窗
     * @public
     */
    visibleDialog: {
      type: Boolean,
      default: false
    },
    /**
     * 弹窗表单打开的配置文件名称，位置在@public/data
     * @public
     */
    name: {
      type: String,
      default: ''
    },
    /**
     * 表单弹窗的标题
     * @public
     */
    title: {
      type: String,
      default: ''
    },
    /**
     * 额外的参数对象
     * @public
     */
    query: {
      type: Object,
      default () {
        return {};
      }
    },
    /**
     * 页面配置文件的api设置【暂未使用】
     * @public
     */
    pageConfigApi: {
      type: Object,
      default () {
        return null;
      }
    },
    /**
     * 表单数据源api设置
     * @public
     */
    dataSourceApi: {
      type: Object,
      default () {
        return null;
      }
    },
    /**
     * 表单默认值api设置
     * @public
     */
    defaultValueApi: {
      type: Object,
      default () {
        return null;
      }
    },
    /**
     * 表单项的后缀
     * @public
     */
    labelSuffix: {
      type: String,
      default: '：'
    },
  },
  data () {
    return {
      config: {
        name: '',
        primaryKey: '',
        mode: {},
        form: [],
      },
      tabPaneHeight: 0,
      loading: false,
      formConfigList: [],
      form: {},
      initForm: {},
      failField: {},
      buttonLoading: false,
      groupFailIndexArray: []
    };
  },
  computed: {
    labelWidthComp () {
      let config = this.config;
      return config.formConfig && config.formConfig.labelWidth ? config.formConfig.labelWidth : '100px';
    },
    hiddenFormItem () {
      return function (item) {
        if (item.visibleFunction) {
          try{
            return new Function('form','field', 'query', item.visibleFunction )(this.form, item.field, this.query);
          }catch(e) {
            console.log('visibleFunction error');
            console.log(e);
          }
        }
        return true;
      };
    },
    disabledButton () {
      return function (button, row) {
        if (button.disabledFunction) {
          try{
            return new Function("row", button.disabledFunction )(row);
          }catch (e) {
            console.log('disabledFunction error');
            console.log(e);
          }
        }
        return button.props && button.props.disabled !== undefined ? button.props.disabled : false;
      };
    },
    visible: {
      get () {
        return this.visibleDialog;

      },
      set (val) {
        this.$emit('update:visibleDialog', val);
      }
    },
    formTitle () {
      if (this.title) {return this.title;}
      return this.config && this.config.title || '';
    },
    rules () {
      let rules = {};
      let formList = cloneJson(this.config.form);
      if (formList && formList.length > 0) {
        for (let i in formList) {
          let validates = formList[i].validate;
          if (validates && validates.length > 0) {
            for(let j in validates) {
              if (validates[j].validatorFunction) {
                validates[j].validator = (rule, value, callback) => { return callback(new Error('')); };
              }
            }
            rules[formList[i].field] = formList[i].validate;
          }
        }
      }
      return rules;
    },
    groupForm () {
      return generateGroupForm(cloneJson(this.config.form));
    },
    primaryKeyValue () {
      return this.query[this.config.primaryKey] || '';
    },
    queryString () {
      return this.query;
    },
    preFormFunction () {
      return this.config && this.config.preFormFunction ? this.config.preFormFunction : '';
    },
    preViewFunction () {
      return this.config && this.config.preViewFunction ? this.config.preViewFunction : '';
    },
    pageConfig () {
      return this.pageConfigApi ? this.pageConfigApi : (this.config && this.config.apiList && this.config.apiList.pageConfigApi ? this.config.apiList.pageConfigApi : null);
    },
    pageConfigUrl () {
      return this.pageConfig && this.pageConfig.url ? this.pageConfig.url : null;
    },
    pageConfigQuery () {
      let query = this.query;
      let row = this.pageConfig && this.pageConfig.query ? this.pageConfig.query : {};
      if (query && row) {
        for (let i in row) {
          if (typeof row[i] === 'string' &&row[i].substr(0, 3) === '$q_' && row[i].length > 3) {
            let field = row[i].substr(3);
            row[i] = query[field];
          }
        }
      }
      return row;
    },
    dataSource () {
      return this.dataSourceApi ? this.dataSourceApi : (this.config && this.config.apiList && this.config.apiList.dataSourceApi ? this.config.apiList.dataSourceApi : null);
    },
    dataSourceUrl () {
      return this.dataSource && this.dataSource.url ? this.dataSource.url : null;
    },
    dataSourceQuery () {
      return function (formList) {
        if (this.dataSource && this.dataSource.queryFunction) {
          try{
            let form = {};
            if (formList && formList.length > 0) {
              for (let i in formList) {
                form[formList[i].field] = formList[i].value;
              }
            }
            return new Function('form','query', this.dataSource.queryFunction)(form, this.query);
          }catch (e) {
            console.log('queryFunction error');
            console.log(e);
          }
        }
        let query = this.query;
        let row = this.dataSource && this.dataSource.query ? cloneJson(this.dataSource.query) : {};
        if (query && row) {
          for (let i in row) {
            if (typeof row[i] === 'string' && row[i].substr(0, 3) === '$q_' && row[i].length > 3) {
              let field = row[i].substr(3);
              row[i] = query[field];
            }
          }
        }
        return row;
      };
    },
    defaultValue () {
      return this.defaultValueApi ? this.defaultValueApi : (this.config && this.config.apiList && this.config.apiList.defaultValueApi ? this.config.apiList.defaultValueApi : null);
    },
    defaultValueUrl () {
      return this.defaultValue && this.defaultValue.url ? this.defaultValue.url : null;
    },
    defaultValueQuery () {
      let query = this.query;
      let row = this.defaultValue && this.defaultValue.query ? cloneJson(this.defaultValue.query) : {};
      if (row) {
        for (let i in row) {
          if (typeof row[i] === 'string' && row[i].substr(0, 3) === '$q_' && row[i].length > 3) {
            let field = row[i].substr(3);
            if (query[field] !== undefined) {
              row[i] = query[field];
            }
          }
        }
      }
      return row;
    },
    buttons () {
      return this.config && this.config.buttons ? this.config.buttons : [];
    },
    viewRequest () {
      return this.form;
    },
    block () {
      return function (item) {
        let times = item === undefined || item.col === undefined ? null : item.col.times;
        if(!times || isNaN(times) || times <= 0) {
          times = 1;
        }
        return times;
      };
    },
    labelWidth () {
      return function (item) {
        let a = item && item.col && item.col.labelWidth ? item.col.labelWidth : (this.config && this.config.formConfig && this.config.formConfig.labelWidth ? this.config.formConfig.labelWidth : null);
        return a;
      };
    },
    lineFeed () {
      return function (item) {
        let lineFeed = item === undefined || item.col === undefined ? null : item.col.lineFeed;
        if (lineFeed !== 'head' && lineFeed !== 'foot' && lineFeed !== 'all') {
          lineFeed = null;
        }
        return lineFeed;
      };

    },
    components: {
      get () {
        let options = this.config;
        return options && options.components ? options.components : [];
      },
      set (components) {
        let options = this.config;
        options.components = components;
      }
    },
  },
  watch: {
    visible: {
      handler (visible, oldVisible) {
        if (visible && visible !== oldVisible) {
          this.getConfig();
        }
      },
      immediate:true
    },
    width: {
      handler (n) {
      },
      immediate:true
    }
  },
  created() {
  },
  mounted () {
    console.log(this.form)
    console.log(this.query)

  },
  methods: {
    /**
     * 设置表单内部pane高度
     * @param {number|string} height 高度
     * @private
     */
    handleFetchPaneHeight (height) {
      this.tabPaneHeight = height;
    },
    /**
     * 弹窗组件关闭时触发
     * @param {string} componentKey 组件名称
     * @private
     */
    handleComponentClose (componentKey) {
      let components = this.components;
      components[componentKey].active = false;
      this.components = Object.assign({}, components);
    },
    /**
     * 生成额外参数
     * @private
     * @param {object} button 按钮配置
     * @param {object} row 表格行数据
     * @param {object} routeQuery 当前路由对象
     * @returns {null|*}
     */
    generateQuery (button, row, routeQuery) {
      if (button.queryFunction) {
        try {
          return new Function('row', 'query', button.queryFunction)(row, routeQuery);
        }catch (e) {
          return null;
        }
      } else {
        let query = button.query;
        if (!query) {
          return null;
        }
        for (let i in query) {
          if (typeof query[i] === 'string' && query[i].substr(0, 3) === '$q_' && query[i].length > 3) {
            let field = query[i].substr(3);
            query[i] = row[field];
          }
        }
        return query;
      }
    },
    /**
     * 公共的询问框方法。
     * @private
     * @param confirmConfig
     * @returns {Promise<unknown>}
     */
    commonConfirm (confirmConfig) {
      return new Promise((resolve, reject) => {
        if (confirmConfig && confirmConfig.message) {
          this.$msgbox({
            title: confirmConfig.title || this.$t('common.tip'),
            message: confirmConfig.message,
            showCancelButton: confirmConfig.showCancelButton || true,
            type: confirmConfig.type || 'warning',
            showClose: confirmConfig.showClose || true,
            confirmButtonText: confirmConfig.confirmButtonText || this.$t('common.confirm'),
            cancelButtonText: confirmConfig.cancelButtonText || this.$t('common.cancel'),
          }).then(() => {
            resolve();
          }).catch(() => {
            reject();
          });
        } else {
          resolve();
        }
      });
    },
    /**
     * 验证表单动作
     * @private
     * @param {object} button 按钮配置
     * @returns {Promise<unknown>}
     */
    validateFormAction (button) {
      return new Promise((resolve, reject) => {
        if (button.actionType === 'save' && (button.validateForm === undefined || button.validateForm !== false)){
          this.$refs.erpPageForm.$refs.form.validate((valid, obj) => {
            this.handleFailValidate({failField: obj});
            if (valid) {
              resolve();
            } else {
              reject();
              return false;
            }
          });
        } else {
          resolve();
        }
      });
    },
    /**
     * 点击按钮动作
     * @private
     * @param {object} button 按钮配置
     * @param {number} buttonIndex 按钮的索引
     */
    handleRowAction (button, buttonIndex) {
      button = cloneJson(button);
      this.commonConfirm(button.confirm)
        .then(() => {
          if (button.actionType === 'dialog') {
            let query = this.generateQuery(button, this.form, this.query);
            let data = this.components;
            if (data) {
              for (let key in data) {
                data[key].active = button.componentKey === key;
                if (button.componentKey === key) {
                  data[key].query = query;
                }
              }
            }
            this.components = Object.assign({}, data);
          } else if (button.actionType === 'save') {
            if (button.queryList) {
              if (button.query){
                for (let i in button.query) {
                  this.form[i] = button.query[i];
                }
              }
              this.$emit('query-list',this.form);
              if (!(button.then && button.then.close === false)) {
                this.handleClose();
              }
              return false;
            }
            let saveApi = button.actionApi || '';
            if (saveApi) {
              this.validateFormAction(button)
                .then(() => {
                  let form = cloneJson(this.form);
                  form = this.pretreatmentForm(form);
                  let query = this.generateQuery(button, form, this.query);
                  form = this.generateForm(button, form, query);

                  this.buttons[buttonIndex].loading = true;
                  request.post(saveApi, form)
                    .then(() => {
                      this.afterSave(button);
                      this.buttons[buttonIndex].loading = false;
                    })
                    .catch(() => {
                      this.buttons[buttonIndex].loading = false;
                    });
                })
                .catch((err) => {
                  console.log(err);
                });
            }
          }
        })
        .catch(() => {});
    },

    /**
     * 按钮在提交前预处理表单
     * @private
     * @param {object} button 按钮配置
     * @param {object} form 表单
     * @param {object} query 额外参数
     * @returns {null|*}
     */
    generateForm (button, form, query) {
      if (button.saveFunction) {
        try {
          return new Function('row', 'query', button.saveFunction)(form, query);
        }catch (e) {
          return null;
        }
      } else {
        return form;
      }
    },
    /**
     * 按钮提交表单之后
     * @private
     * @param {object} button [按钮配置](../eg/Button.html#formButton)
     * @returns {boolean}
     */
    afterSave (button) {
      if (button.actionType !== 'save') {
        return false;
      }
      if (button.then || button.then === undefined) {
        if (button.then === undefined) {
          toast({
            message: this.$t('common.saveSuccess'),
            type: 'success'
          });
        } else if (button.then.toast && button.then.toast.message) {
          toast(button.then.toast);
        }
        if ((button.then === undefined && button.then.refreshList === undefined) || button.then.refreshList !== false) {
          this.$emit('refresh');
        }
        if ((button.then === undefined && button.then.close === undefined) || button.then.close !== false) {
          this.handleClose();
        }
      }
    },
    /**
     * 更新表单中其他字段的值
     * @private
     * @param obj
     */
    handleValueChange (obj) {
      let form = this.form;
      if (obj.field) {
        form[obj.field] = obj.value;
      }
    },
    /**
     * 关闭表单
     * @private
     */
    handleClose() {
      this.$emit('close');
    },
    /**
     * 验证失败时触发
     * @private
     */
    handleFailValidate (failField) {
      if (!failField) {
        failField = {};
      }
      let failFieldObj = failField.failField;
      let groupForm = this.groupForm;
      let groupFailIndexArray = [];
      if (groupForm && groupForm.length > 0) {
        for (let i in groupForm) {
          if (groupForm[i].items && groupForm[i].items.length > 0) {
            for (let j in groupForm[i].items) {
              if(groupForm[i].items[j].items && groupForm[i].items[j].items.length > 0) {
                for (let k in groupForm[i].items[j].items) {
                  if (failFieldObj && failFieldObj[groupForm[i].items[j].items[k].field] !== undefined) {
                    groupFailIndexArray.push(parseInt(i));
                  }
                }
              }
            }
          }
        }
      }
      this.groupFailIndexArray = uniqueArray(groupFailIndexArray);
    },
    /**
     * 获取服务的页面配置
     * @private
     * @returns {Promise<unknown>}
     */
    getServerPageConfig () {
      return new Promise( (resolve, reject) => {
        if (this.pageConfigUrl) {
          request.post(this.pageConfigUrl, this.pageConfigQuery)
            .then(res => {
              this.config = res.data;
              resolve();
            })
            .catch(err => {
              this.loading = false;
              reject(err);
            });
        } else {
          try{
            this.config = require('@public/data/' + this.name + '.json');
            resolve();
          } catch (e) {
            this.loading = false;
            reject(e);
          }
        }
      });
    },
    /**
     * 获取服务端的表单表单数据源
     * @private
     * @param {array} formList 表单配置
     * @returns {Promise<unknown>}
     */
    getServerDataSource (formList) {
      return new Promise( (resolve, reject) => {
        getServerDataSource(formList, this.dataSource, this.query, this.preViewFunction, '')
          .then((res) => {
            resolve(res.formList);
            return res.formList;
          })
          .catch(err => {
            console.log(err);
            reject(err);
          });
      });
    },
    /**
     * 获取服务端的表单默认值
     * @private
     * @param {array} formList 表单配置
     * @returns {Promise<unknown>}
     */
    getDefaultValue (formList) {
      return new Promise((resolve, reject) => {
        if (this.defaultValueUrl) {
          request.post(this.defaultValueUrl, this.defaultValueQuery)
            .then(res => {
              let form = res.data;
              form = this.pretreatmentView(form);
              if (formList && formList.length > 0) {
                for (let i in formList) {
                  if (form) {
                    for (let j in form) {
                      if (formList[i].field === j) {
                        formList[i].value = form[j];
                      }
                    }
                  }
                }
              }
              resolve(formList);
              return formList;
            })
            .catch(err => {
              this.loading = false;
              reject(formList);
              return formList;
            });
        } else {
          resolve(formList);
          return formList;
        }
      });
    },
    /**
     * 页面加载时，获取数据源，获取表单默认值，以及清除验证
     * @private
     * @returns {Promise<void>}
     */
    async getConfig() {
      this.loading = true;
      await this.getServerPageConfig().catch(err => err);
      let config = this.config;
      let formList = cloneJson(config.form);
      formList = await this.getDefaultValue(formList);
      formList = await this.getServerDataSource(formList);
      config.form = formList;
      this.formConfigList = formList;
      let initForm = this.generateNewForm(formList);
      this.form = cloneJson(initForm);
      this.initForm = initForm;
      this.loading = false;
      this.$nextTick(() => {
        this.$refs.erpPageForm && this.$refs.erpPageForm.$refs.form && this.$refs.erpPageForm.$refs.form.clearValidate();
      });
    },
    /**
     * 通过表单配置生成表单默认值
     * @private
     * @param {array} formList  表单配置
     * @returns {{}}
     */
    generateNewForm (formList) {
      return generateNewForm(formList, this.query, this.form);
    },
    /**
     * 是否显示表单
     * @private
     * @param {object} item 表单项配置
     * @param {object} query 额外参数
     * @returns {boolean|*}
     */
    visibleFunc (item, query) {
      if (item.visibleFunction) {
        let form = this.form;
        let field = item.field;
        try{
          return new Function('form','field', 'query', item.visibleFunction )(form, field, query);
        }catch(e) {
          return true;
        }
      }
      return true;
    },
    /**
     * 获取详情
     * @private
     */
    getDetail () {
      let updateDetail = this.config && this.config.apiList && this.config.apiList.updateDetail ? this.config.apiList.updateDetail : '';
      if (updateDetail) {
        request.post(updateDetail, {[this.config.primaryKey]: this.primaryKeyValue})
          .then(res => {
            let form = res.data;
            form = this.pretreatmentView(form);
            let initForm = cloneJson(this.initForm);
            this.form = Object.assign(initForm, form);
          });
      }
    },
    /**
     * 保存表单
     * @private
     * @param form
     */
    handleSave(form) {
      form = this.pretreatmentForm(form);
      this.buttonLoading = true;
      if (this.mode === 'create') {
        let createApi = this.config && this.config.apiList && this.config.apiList.create ? this.config.apiList.create : '';
        request.post(createApi, form)
          .then(() => {
            toast({
              message: this.$t('common.createSuccess'),
              type: 'success'
            });
            this.$emit('refresh');
            this.handleClose();
            this.buttonLoading = false;
          })
          .catch(() => {
            this.buttonLoading = false;
          });
      } else if (this.mode === 'update') {
        let updateApi = this.config && this.config.apiList && this.config.apiList.update ? this.config.apiList.update : '';
        request.post(updateApi, form)
          .then(() => {
            toast({
              message: this.$t('common.updateSuccess'),
              type: 'success'
            });
            this.$emit('refresh');
            this.handleClose();
            this.buttonLoading = false;
          })
          .catch(() => {
            this.buttonLoading = false;
          });
      }
    },
    /**
     * 在提交前预处理表单
     * @private
     * @param {object} form 表单对象
     * @returns {*}
     */
    pretreatmentForm (form) {
      if (this.preFormFunction) {
        return new Function('form', this.preFormFunction )(form);
      }
      return form;
    },
    /**
     * 在获取默认值后进一步预处理表单
     * @private
     * @param {object} form 表单对象
     * @returns {*}
     */
    pretreatmentView (form) {
      if (this.preViewFunction) {
        return new Function('form', this.preViewFunction )(form);
      }
      return form;
    },
    /**
     * 更新表单其他值
     * @param {object} fieldObj 表单对象
     * @public
     */
    handleUpdateField (fieldObj) {
      let form = this.form;
      if (form) {
        for (let i in form) {
          if (fieldObj[i] !== undefined) {
            form[i] = fieldObj[i];
          }
        }
      }
    },
    /**
     * 通过表单类型过滤字段
     * @param {object} item 表单项
     * @param {object} query 额外参数
     * @public
     */
    filterFieldByMode (item, query) {
      return this.visibleFunc(item, query);
    },
    /**
     * 更新tab分页的list的配置
     * @private
     * @param options
     * @param item
     */
    changeOptions (options, item) {
      let formList = this.config.form;
      if (formList && formList.length > 0) {
        for (let i in formList) {
          if (formList[i].field === item.field) {
            formList[i].options = options;
          }
        }
      }
    }
  }
};
</script>

<style lang="scss" scoped>
    $primaryColor: var(--primary-color);
    .hasHeader{
        &::v-deep {
            &.el-card {
                .el-card__body {
                    padding-top: 10px;
                }
            }
        }
    }
    .box-title {
        color: $primaryColor;
        font-weight: bold;
    }
    $fontSize: var(--font-size);

</style>
